package com.nf.controller;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
//@WebFilter("*.do")
public class SecurityFilter implements Filter {
    private String allowUrl=null;//自定义两个全局变量
    String[] allowUrls=null;

    @Override
    //init初始化运行一次
    public void init(FilterConfig filterConfig) throws ServletException {
        allowUrl=filterConfig.getInitParameter("list");//获取配置文件中list的数据
        allowUrls=allowUrl.split(",");//用于获取list的数据
    }

    @Override
    //doFilter每次执行都会运行一次
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;//强制转换
        HttpServletResponse resp=(HttpServletResponse)response;
        String requestURI=req.getRequestURI();//调用系统方法

        if (allow(requestURI)){//调用自定义方法
            chain.doFilter(req,resp);//放行
            return;//返回到这往下执行
        }
        HttpSession session=req.getSession();//调用一个会话
        String obj=(String)session.getAttribute("user");//把数据从会话取出来
        if (obj==null||obj.isEmpty()){//会话传过来的数据等于null或者数据等于空
            resp.sendRedirect("/login");//去到登录界面
        }else{
            chain.doFilter(req,resp);//放行
        }
    }

    @Override
    //destroy结束运行一次
    public void destroy() {

    }
    private boolean allow(String requestUri){
        boolean result=false;//申明变量
        for (String url:allowUrls){//判断里面有没有逗号
            result=url.equals(requestUri);
            if (result==true){
                break;//暂停
            }
        }
        return result;
    }
}
